package org.study.local.boot.service.impl;

import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.study.local.boot.config.LocalFileProperties;
import org.study.local.boot.service.LocalFileService;
import org.study.local.boot.util.LocalUploadUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;

/**
 * 作用描述
 *
 * @author doveylovey
 * @version v1.0.0
 * @email 1135782208@qq.com
 * @date 2023年12月12日
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class LocalFileServiceImpl implements LocalFileService {
    private final LocalFileProperties localFileProperties;

    @Override
    public Map<String, Object> upload(MultipartFile file) {
        Map<String, Object> retMap = Maps.newLinkedHashMap();
        // 校验文件大小
        if (LocalUploadUtils.isFileSizeOver(file.getSize(), LocalUploadUtils.ALLOWED_IMG_SIZE)) {
            retMap.put("code", "9999");
            retMap.put("msg", "文件大小不能大于" + LocalUploadUtils.ALLOWED_IMG_SIZE + "MB");
            return retMap;
        }
        // 获取文件后缀并校验
        String suffix = LocalUploadUtils.getMultipartFileSuffix(file);
        if (!LocalUploadUtils.isFileTypeAllowed(suffix, LocalUploadUtils.ALLOWED_IMG_TYPE)) {
            retMap.put("code", "9999");
            retMap.put("msg", "请选择" + JSON.toJSONString(LocalUploadUtils.ALLOWED_IMG_TYPE) + "格式的图片");
            return retMap;
        }
        String group = DateTimeFormatter.ofPattern(DatePattern.PURE_DATE_PATTERN).format(LocalDate.now());
        String filename = LocalUploadUtils.upload(localFileProperties.getUploadFolder() /*+ File.separator*/ + group, file);
        retMap.put("code", "0000");
        retMap.put("msg", "文件上传成功");
        retMap.put("filename", filename);
        retMap.put("localPath", localFileProperties.getUploadFolder() + filename);
        retMap.put("filePath", localFileProperties.getWebPathPrefix() + "/" + filename);
        retMap.put("fileUrl", "http://127.0.0.1:8888" + localFileProperties.getWebPathPrefix() + "/" + filename);
        return retMap;
    }
}
